#!/usr/bin/perl

use warnings;
use strict;
use FindBin;
use DateTime;
use Getopt::Long;
use lib "$FindBin::Bin/../lib";
use ReefStats::Schema::ReefStatsDB;

my ( $upper_date, $lower_date );

GetOptions( 'min-date=s' => \$lower_date, 'max-date=s' => \$upper_date )
  or die $!;

if ($upper_date) {
    my ( $year, $month, $day ) = split /\D/, $upper_date;
    $upper_date = DateTime->new( year => $year, month => $month, day => $day );
}
else {
    $upper_date =
      DateTime->now()->set_time_zone('local')->subtract( days => 1 );
}

if ($lower_date) {
    my ( $year, $month, $day ) = split /\D/, $lower_date;
    $lower_date = DateTime->new( year => $year, month => $month, day => $day );
}
else {
    $lower_date = $upper_date->clone->subtract( days => 1 );
}

my $schema = ReefStats::Schema::ReefStatsDB->connect_via_config();

my $maillog                = $schema->resultset('Maillog');
my $blacklisted_reasonexts = $schema->resultset('BlacklistedReasonextsHourly');

my $summary = $maillog->search(
    {
        timestamp => { -between => [ $lower_date, $upper_date ] },
        reason    => 'Blacklist'
    },
    {
        select => [
            { hour => 'timestamp' },
            { date => 'timestamp' },
            qw( cluster domain recipient action reasonext ),
            { count => '*' },
        ],
        as       => [qw( hour day cluster domain user action reasonext number )],
        group_by => [
            'hour(timestamp)', 'date(timestamp)', qw( cluster domain recipient action reasonext )
        ],
    }
);

my $summarized = $blacklisted_reasonexts->search(
    { day => { -between => [ $lower_date, $upper_date ] }, },
);
while ( my $row = $summarized->next() ) {
    $row->delete();
}

while ( my $row = $summary->next() ) {
#    print '[',
#      join( '][',
#        map { $row->get_column($_) }
#          qw(hour day cluster domain user action reasonext number) ),
#      "]\n";
    $blacklisted_reasonexts->create(
        {
            map { $_ => $row->get_column($_) }
              qw(hour day cluster domain user action reasonext number )
        }
    );
}

